export default (Vue) => {
  /**
   * 身份证号码过滤
   */
  Vue.filter("idMask", (val) => {
    if (!val) return "";
    return val.replace(/^(\d{3})(.*?)([\dx]{4})$/, (match, p1, p2, p3) => {
      return `${p1}${"*".repeat(11)}${p3}`;
    });
  });

  /**
   * 金额过滤
   */
  Vue.filter("amount", (val) => {
    val = val.toString().replace(/\$|\,/g, "");
    if (isNaN(val)) {
      val = "0";
    }
    let sign = val == (val = Math.abs(val));
    val = Math.floor(val * 100 + 0.50000000001);
    let cents = val % 100;
    val = Math.floor(val / 100).toString();
    if (cents < 10) {
      cents = "0" + cents;
    }
    for (let i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
      val =
        val.substring(0, val.length - (4 * i + 3)) +
        "," +
        val.substring(val.length - (4 * i + 3));
    }
    return (sign ? "" : "-") + val + "." + cents;
  });

  /**
   * 日期时间过滤器
   * @param {Object} time
   * @param {Object} format
   */
  Vue.filter("formatDate", function (time, format) {
    let date = new Date(time);
    return formatdate(date, format);
  });

  function padLeftZero(str) {
    return ("00" + str).substr(str.length);
  }

  function formatdate(date, fmt) {
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    }
    let o = {
      "M+": date.getMonth() + 1,
      "d+": date.getDate(),
      "h+": date.getHours(),
      "m+": date.getMinutes(),
      "s+": date.getSeconds(),
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        let str = o[k] + "";
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? str : padLeftZero(str)
        );
      }
    }
    return fmt;
  }
};
